#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#from google.appengine.ext import db
#from google.appengine.api import urlfetch 
import urllib 
import urllib2  
 

def NMDictFromJonson(jsStr):
    (null,true, false)=(None, True, False) #@UnusedVariable
    return eval(jsStr)
    
class uriWithParms(dict):
    _baseUri=""
    def getUrl(self):
        return "%s%s%s" %(self.getBaseUri(), '' if len(self)==0 else'?', urllib.urlencode(self)) 
        return self.getBaseUri()+ urllib.urlencode(self)
    def setBaseUri(self, str):
        self._baseUri=str
    def getBaseUri(self):
        return self._baseUri
class uriGstaticMaps(uriWithParms):
    """http://code.google.com/apis/maps/documentation/staticmaps/ 
    if a single marker is needed just instantiate and set.Markersicon will do ie gm.setMarkersIcon('fire|FF0000','| 38.254, 23.268|') 
    """ 
    _baseUri="http://maps.google.com/maps/api/staticmap" 
    _chartMarkerUri="http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=" #fire|FF0000"  
    
    def __init__(self,*args, **kargs):
        uriWithParms.__init__(self,*args, **kargs)  
        if self.get('sensor', None) is None:self.setSensor() 
        if self.get('size', None) is None:self.setSize(400, 400) 
    def setBaseUri(self, str):pass 
    def setZoom(self, val):self['zoom']=str(val) 
    def setCenter(self, val):self['center']=str(val) 
    def setSize(self, width, height): 
        self['size']="%sx%s" %(str(width), str(height)) 
    def setSensor(self, val='false'):self['sensor']=val
    def setMarkersIcon(self, iconName, rest):  
        iconName= iconName.replace('|', '%7C') #'%257C'
        self['markers']='icon:'+self._chartMarkerUri+iconName+rest  
class uriGTranslate(uriWithParms):
    """http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje""" 
    _baseUri="http://ajax.googleapis.com/ajax/services/language/translate"  
    """" 
    ?v=1.0&q=hello%20world&langpair=en%7Cit 
    http://ajax.googleapis.com/ajax/services/language/translate 
    """ 
    def __init__(self,*args, **kargs):
        uriWithParms.__init__(self,*args, **kargs) 
        self['v']='1.0' 
    def setQuery(self, q="", ip='193.92.180.166', langpair="en|el"): 
        self["q"]=q
        if ip !='':self['ip']=ip 
        self['langpair']=langpair 
    def setBaseUri(self, str):pass 

def GtranslateFetch(txt, langpair):
    """response like: {"responseData": {"translatedText":"Η σύσκεψη αλεπού"}, "responseDetails": null, "responseStatus": 200}"""
    url=uriGTranslate()
    url.setQuery(q=txt, langpair=langpair)
    result = FetchJonson(url.getUrl())  
    if  isinstance(result, dict): 
        RS=result['responseStatus'] 
        if RS==200:
            return result['responseData']['translatedText']
        else:
            return ['Gtranslate Response :' + str(RS) ] 
    else:
        return result 
     
 
def GgeocodeFetch(lat, lng):  
    url ="http://maps.google.com/maps/api/geocode/json?latlng=XX,YY&sensor=false&language=el"  
    url=url.replace('XX', str(lat)).replace('YY', str(lng)) 
    result=FetchJonson(url) 
    if isinstance(result, dict):
        RS=result['status']   
        if RS == "OK":
            return result['results'][0].get('formatted_address', '')
        else:
            return ['GgeocodeFetch Result Status:'+ RS ]   
    else:
        return result
    return '' 
def FetchJonson(url):
    try:
        result=urllib2.urlopen(url) 
        if result.code == 200:return NMDictFromJonson(result.read() ) 
        else:  return [result.code]
    except :
        pass
    return [-999]
   
